import { reactive } from 'vue'
import request from '@/utils/request'
import { Ilist } from 'mock/user'
import { ElMessage } from 'element-plus'

type TState = 'success' | 'error'
interface IMessage {
  type: TState
  msg: string
}

const state = reactive({
  list: [] as Ilist[],
  total: 0,
  listQuery: {
    limit: 5,
    page: 1
  },
  loading: false
})

function useList () {
  const getList = (): Promise<IMessage> => {
    state.loading = true

    return request({
      method: 'get',
      url: '/getUsers',
      params: state.listQuery
    })
      .then(({ data, total }: any): IMessage => {
        state.list = data
        state.total = total
        return { type: 'success', msg: '获取/更新成功' }
      })
      .catch((): IMessage => ({ type: 'error', msg: '获取/更新失败' }))
      .finally(() => { state.loading = false })
  }

  const delItem = (id: string): Promise<IMessage> => {
    state.loading = true

    return request({
      method: 'get',
      url: '/deleteUser',
      params: { id }
    })
      .then((): IMessage => ({ type: 'success', msg: '删除成功' }))
      .catch((): IMessage => ({ type: 'error', msg: '删除失败' }))
      .finally(() => { state.loading = false })
  }

  const updateList = (promise: Promise<IMessage>) => {
    return promise
      .then(({ type, msg }) => {
        ElMessage[type](msg)
        return type === 'success' ? getList() : { type: 'done' }
      })
      .then(({ type }) => type === 'error' && ElMessage[type]('列表刷新失败'))
  }

  return { state, getList, delItem, updateList }
}

interface IData {
  name: string
  age: number | undefined
}


function useItem () {
  const itemData = reactive<{ data: IData }>({
    data: {
      name: '',
      age: undefined
    }
  })

  const getItem = (id: string): void => {
    request({
      url: '/getUser',
      method: 'get',
      params: { id }
    })
      .then(({ data }) => {
        itemData.data = data
      })
      .catch(() => { })
  }

  const updateItem = (id: string): Promise<IMessage> => {
    return request({
      url: '/updateUser',
      method: 'post',
      data: { id, data: itemData.data }
    })
      .then((): IMessage => {
        return ({ type: 'success', msg: '修改成功' })
      })
      .catch((): IMessage => ({ type: 'error', msg: '修改失败' }))
  }

  const createItem = (): Promise<IMessage> => {
    return request({
      url: '/createUser',
      method: 'post',
      data: itemData.data
    })
      .then((): IMessage => ({ type: 'success', msg: '新增成功' }))
      .catch((): IMessage => ({ type: 'error', msg: '新增失败' }))
  }

  return { itemData, getItem, updateItem, createItem }
}

export { useList, useItem }